#!/bin/python
#coding=utf8
import MySQLdb
from ftplib import FTP
import commands
import re
import datetime
from hynmath import loadConfig

# 全局变量
today = datetime.date.today()
config = {}
loadConfig(config,'config.txt')

# 自定义函数
def getResultFromFTP(item,user,password,ip,path,target):
    ftp = FTP(ip,user,password)
    ftp.cwd(path)
    filesList = ftp.nlst(target)
    latestFileName = filesList[len(filesList)-1]
    pattern = re.compile(r'([0-9]+[0-9-]+)')
    m = pattern.search(latestFileName)
    result = m.group(1)
    return result

def getResultFromMySQL(item,user,password,ip,path,target):
    (database,table,id) = path.split('.')
    cmd = 'mysql -u%s -p%s -h%s %s -e "select %s from %s where %s like \'%%%s\';"' % (user,password,ip,database,target,table,id,item)
    result = commands.getoutput(cmd).split('\n')[1]
    return result

# 创建数据库连接
connection = MySQLdb.connect(host=config['host'], user=config['user'], passwd=config['password'], db=config['database'], init_command=config['encoding'])
cursor = connection.cursor()

# 清除之前产生的数据
sql = "truncate mlogdate"
cursor.execute(sql)

# 获取监控条目
sql = "select STATION,ITEM,TYPE,USER,PASSWORD,IP,PATH,TARGET,SAVETYPE from mstations where ISMONITOR=1"
cursor.execute(sql)
rows = cursor.fetchall()

# 监控主逻辑
for row in rows:
    # 获取监控信息
    station  = row[0]
    item     = row[1]
    type     = row[2]
    user     = row[3]
    password = row[4]
    ip       = row[5]
    path     = row[6]
    target   = row[7]
    savetype = row[8]

    # 获取监控结果
    print item,user,password,ip,path,target    
    if type == 'FTP':
        result = getResultFromFTP(item,user,password,ip,path,target)
    if type == 'MYSQL':
        result = getResultFromMySQL(item,user,password,ip,path,target)
    length = len(result)
    result += (14 - length) * '0'

    # 保存结果
    sql = "insert into mlogdate (UPTIME,STATION,LOGTYPE,SAVETYPE,LOGDATE) values ('%s','%s','%s','%s','%s')" % (today,station,item,savetype,result)
    cursor.execute(sql)
    
# 生成每日报表
sql = "call sp_CalcDailyReport()"
cursor.execute(sql)
